package com.example.algorithms;

public class Search {

    // 二分查找算法
    public static int binarySearch(int[] array, int number){
        int low = 0, high = array.length - 1;
        while (true){
            int middle = (low + high) / 2;
            int value = array[middle];
            if(value == number){
                return middle;
            }
            else if(high <= low){
                return -1;
            }
            else if(number > value){
                low = middle+1;
                continue;
            }else {
                high = middle-1;
                continue;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 9};
        System.out.println("index:" + binarySearch(arr, 1));
        System.out.println("index:" + binarySearch(arr, 2));
        System.out.println("index:" + binarySearch(arr, 3));
        System.out.println("index:" + binarySearch(arr, 4));
        System.out.println("index:" + binarySearch(arr, 5));
        System.out.println("index:" + binarySearch(arr, 6));
        System.out.println("index:" + binarySearch(arr, 7));
        System.out.println("index:" + binarySearch(arr, 8));
        System.out.println("index:" + binarySearch(arr, 9));
        System.out.println("index:" + binarySearch(arr, 10));
        System.out.println(arr.getClass().getComponentType());
    }
}
